<script>
import AmountInput from '@/components/amountInput/index'
import MyImage from '@/components/ImageWithUpload/index'
import ImageWithUpload from '@/components/ImageWithUpload/default'
import nzhcn from 'nzh/cn'
import dayjs from 'dayjs'
import { companyInfo, updateCompanyInfo } from '@/api/basic'
import { mapGetters } from 'vuex'
import RichTextEditor from '@/components/RichTextEditor/RichTextEditor.vue'
export default {
  components: {
    AmountInput,
    ImageWithUpload,
    MyImage,
    RichTextEditor
  },
  data() {
    return {
      isLoading: false,
      isUpdating: false,
      isEdit: false,
      draft: {
        businessLicense: '',
        businessLicenseCode: '',
        registeredCapital: 0,
        businessLicenseBeginDate: null,
        businessLicenseEndDate: null,
        logo: '',
        companyName: '',
        registeredAddress: '',
        introduction: '',
        companyImages: [],
        companyAbbreviationName: '',
        qrcodeLogo: ''
      },
      formRules: {
        registeredCapital: [
          {
            validator: (_, value, callback) => {
              const p = parseFloat(value)
              if (typeof p !== 'number' || isNaN(p)) {
                return callback('请输入注册资金')
              }

              if (p <= 0) {
                return callback('注册资金必须大于0')
              }

              callback()
            },
            trigger: ['blur']
          }
        ],
        businessLicenseBeginDate: [
          {
            validator: (_, value, callback) => {
              if (!(value instanceof Date)) { return callback() }

              if (this.draft.businessLicenseEndDate instanceof Date) {
                if (value.getTime() >= this.draft.businessLicenseEndDate.getTime()) { return callback(new Error('成立时间必须小于到期时间')) }

                return callback()
              }

              return callback()
            },
            trigger: ['blur', 'change']
          }
        ],
        businessLicenseEndDate: [
          {
            validator: (_, value, callback) => {
              if (!(value instanceof Date)) { return callback() }

              if (this.draft.businessLicenseBeginDate instanceof Date) {
                if (value.getTime() <= this.draft.businessLicenseBeginDate.getTime()) { return callback(new Error('到期时间必须大于成立时间')) }

                return callback()
              }

              return callback()
            },
            trigger: ['blur', 'change']
          }
        ],
        businessLicense: [
          { required: true, message: '请上传营业执照', trigger: ['blur', 'change'] }
        ],
        logo: [
          { required: true, message: '请上传公司logo', trigger: ['blur', 'change'] }
        ],
        companyName: [
          { required: true, message: '请填写公司名称', trigger: ['blur', 'change'] }
        ]
      },
      companyInfo: null,
      companyInfoBackup: null,

      autoCompletion: false,

      styles: {
        height: '60px',
        width: '60px'
      },
      fileList: []
    }
  },
  watch: {
    draft: {
      handler(v) {
        console.log(v)
      },
      deep: true
    }
  },

  computed: {
    ...mapGetters(['defaultCompany']),
    data() {
      if (!this.autoCompletion) return {}

      return {
        analysis: 1,
        type: 'recognition'
      }
    },
    businessLicenseEndDateFormat() {
      const { businessLicenseEndDate } = this.draft
      if (!(businessLicenseEndDate instanceof Date)) return 'yyyy-MM-dd'

      if (dayjs(businessLicenseEndDate).isBefore('2099-01-01', 'day')) { return 'yyyy-MM-dd' }

      return '长期'
    }
  },
  created() {
    this.initData()
  },
  methods: {
    deleteBusinessLicene(delFn) {
      this.$confirm('确定删除营业执照吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(delFn)
    },
    deleteBusinessLogo(delFn) {
      this.$confirm('确定删除LOGO吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(delFn)
    },
    uploadCompanyPhotoSuccess(e) {
      this.draft.companyImages.push(e.data.path)
    },

    uploadCompanyPhotoExceed(e) {
      this.$message.error('最多可上传3张公司照片')
    },

    onBeforeRemoveCompanyPhoto(e) {
      return new Promise((resolve, reject) => {
        this.$confirm('是否删除该张图片', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },

    onCompanyPhotoRemove(e) {
      const url = e?.response?.data?.path || e.url
      this.draft.companyImages = this.draft.companyImages.filter(item => item !== url)
    },

    handleBusinessLiceneAnalysis(data) {
      console.log(data)
      if (!this.autoCompletion) return

      const result = data?.data?.analysis?.result

      if (!result) return

      if (typeof result.registration_number === 'string') {
        this.draft.businessLicenseCode = result.registration_number
      }

      if (typeof result.registered_capital === 'string') {
        const capital = nzhcn.decodeB(result.registered_capital)
        if (typeof capital === 'number' && !isNaN(capital)) { this.draft.registeredCapital = capital }
      }

      if (typeof result.name === 'string') this.draft.companyName = result.name

      if (typeof result.found_date === 'string') {
        const date = dayjs(result.found_date).toDate()
        if (!isNaN(date.getTime())) this.draft.businessLicenseBeginDate = date
      }

      if (
        typeof result.issue_date === 'string' &&
        result.issue_date.trim() !== ''
      ) {
        this.draft.businessLicenseEndDate = dayjs(result.issue_date).toDate()
      } else if (
        typeof result.business_term === 'string' &&
        result.business_term.trim() !== '' &&
        result.business_term.includes('至长期')
      ) {
        this.draft.businessLicenseEndDate = dayjs('2099-01-01').toDate()
      }
    },
    handleEdit() {
      this.companyInfoBackup = { ...this.draft }
      this.companyPhotoFormat()
      this.isEdit = true
    },
    companyPhotoFormat() {
      this.fileList = this.companyInfoBackup.companyImages.map((item, index) => {
        return {
          name: `company_photo_${index + 1}`,
          url: item
        }
      })
    },
    handleCancelEditing() {
      this.draft = { ...this.companyInfoBackup }
      this.companyInfoBackup = null
      this.$refs.form.resetFields()
      this.isEdit = false
    },
    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs.form?.validate?.((flag) => {
          if (flag) return resolve()
          reject(new Error('请正确输入所有信息'))
        }) ?? resolve()
      })
    },
    async saveDraft() {
      try {
        await this.validateForm()
        const params = this.buildParams()
        const now = dayjs(new Date()).format('YYYY-MM-DD')
        const targetTime = dayjs(params.licEndDate).format('YYYY-MM-DD')
        if (now > targetTime) return this.$message.error('营业执照到期时间不得小于当前时间')
        this.isUpdating = true

        const result = await updateCompanyInfo(params)

        if (result.code !== 200) throw new Error(result.message ?? '修改失败')

        this.isUpdating = false
        this.isEdit = false

        await this.initData()

        this.$message.success('修改成功')
      } catch (e) {
        this.isUpdating = false
        this.$message.error(e.message)
      }
    },
    buildParams() {
      const {
        companyName,
        logo,
        introduction,
        businessLicense,
        registeredAddress,
        registeredCapital,
        businessLicenseBeginDate,
        businessLicenseEndDate,
        businessLicenseCode,
        companyImages,
        companyAbbreviationName,
        qrcodeLogo
      } = this.draft

      return {
        name: companyName,
        logo,
        introduction,
        businessLicensePath: businessLicense,
        licAddress: registeredAddress,
        licRegCapital: registeredCapital,
        licFoundDate: this.dateFormatter(businessLicenseBeginDate),
        licEndDate: this.dateFormatter(businessLicenseEndDate),
        licNo: businessLicenseCode,
        company_images: JSON.stringify(companyImages),
        abbreviation: companyAbbreviationName,
        qrcode_logo: qrcodeLogo
      }
    },
    deserialize(data) {
      if (data === null) return
      const {
        name,
        introduction,
        logo,

        licAddress,
        licEndDate,
        licFoundDate,
        licNo,
        licRegCapital,
        businessLicensePath,
        company_images,
        abbreviation,
        qrcode_logo
      } = data

      return {
        companyName: name,
        introduction,
        logo,

        businessLicense: businessLicensePath,
        registeredAddress: licAddress,
        registeredCapital: licRegCapital,
        businessLicenseBeginDate: this.dateParser(licFoundDate),
        businessLicenseEndDate: this.dateParser(licEndDate),
        businessLicenseCode: licNo,
        companyImages: company_images ? JSON.parse(company_images) : [],
        companyAbbreviationName: abbreviation,
        qrcodeLogo: qrcode_logo
      }
    },
    dateFormatter(date) {
      return date === null || date === undefined
        ? null
        : dayjs(date).format('YYYY-MM-DD')
    },
    dateParser(date) {
      return date === null || date === undefined ? null : dayjs(date).toDate()
    },

    async getCompanyInfo() {
      const result = await companyInfo(this.defaultCompany?.id)

      if (result.code !== 200) { throw new Error(result.message ?? '获取公司信息失败') }

      this.companyInfo = result.data
      this.draft = this.deserialize(this.companyInfo)
    },
    async initData() {
      try {
        this.isLoading = true
        await this.sleep(300)
        await this.loadData()
        this.isLoading = false
      } catch (e) {
        this.isLoading = false
        this.$message.error('加载公司信息失败')
      }
    },
    async loadData() {
      await Promise.allSettled([this.getCompanyInfo()])
    }
  }
}
</script>

<template>
  <div class="app-container companyinfo-update-register-container">
    <div class="app-container-item">
      <svg-icon icon-class="company" style="font-size: 34px" />
      <h3 style="margin-left: 4px">企业信息修改</h3>
    </div>
    <el-form
      v-if="draft"
      ref="form"
      label-width="180px"
      label-position="right"
      :model="draft"
      :rules="formRules"
      :disabled="isLoading || isUpdating || !isEdit"
      class="app-container-enterpriseupdate-form"
    >
      <el-form-item label="营业执照" prop="businessLicense">
        <ImageWithUpload
          v-model="draft.businessLicense"
          :disabled="!isEdit"
          :style="styles"
          :handle-delete="deleteBusinessLicene"
          :data="data"
          @success="handleBusinessLiceneAnalysis"
        />
        <el-switch
          v-if="isEdit"
          v-model="autoCompletion"
          style="display: block; margin-top: 14px"
          active-color="#13ce66"
          inactive-color="#d0d0d0"
          active-text="自动识别营业执照"
        />
      </el-form-item>
      <el-form-item label="公司LOGO" prop="logo">
        <ImageWithUpload
          v-model="draft.logo"
          :disabled="!isEdit"
          :handle-delete="deleteBusinessLogo"
          :style="styles"
        />
      </el-form-item>
      <el-form-item label="二维码logo" prop="qrcodeLogo">
        <ImageWithUpload
          v-model="draft.qrcodeLogo"
          :disabled="!isEdit"
          :style="styles"
        />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="draft.companyName"
          style="width: 480px;"
          placeholder="请填写公司名称"
        />
      </el-form-item>
      <el-form-item label="公司名简称" prop="companyAbbreviationName">
        <el-input
          v-model="draft.companyAbbreviationName"
          style="width: 480px;"
          placeholder="请填写公司简称"
        />
      </el-form-item>
      <el-form-item label="公司注册地址" prop="registeredAddress">
        <el-input
          v-model="draft.registeredAddress"
          style="width: 480px;"
          placeholder="请填写公司注册地址"
        />
      </el-form-item>
      <el-form-item label="公司注册资金" prop="registeredCapital">
        <AmountInput
          v-model="draft.registeredCapital"
          style="width: 480px;"
          placeholder="请填写公司注册资金"
        />
      </el-form-item>
      <el-form-item label="公司介绍" prop="introduction">
        <RichTextEditor
          v-if="isEdit"
          v-model="draft.introduction"
          style="width: 800px;"
        />

        <div
          v-else
          class="introduction"
          v-html="draft.introduction"
        />
        <!--        <el-input-->
        <!--          v-model="draft.introduction"-->
        <!--          style="width: 560px"-->
        <!--          placeholder="请填写公司介绍"-->
        <!--          type="textarea"-->
        <!--          maxlength="200"-->
        <!--          show-word-limit-->
        <!--          :autosize="{ minRows: 2, maxRows: 4 }"-->
        <!--        />-->
      </el-form-item>

      <el-form-item label="营业执照号" prop="businessLicenseCode">
        <el-input
          v-model="draft.businessLicenseCode"
          style="width: 480px;"
          placeholder="请填写营业执照号"
        />
      </el-form-item>
      <el-form-item label="营业执照成立日期" prop="businessLicenseBeginDate">
        <el-date-picker
          v-model="draft.businessLicenseBeginDate"
          style="width: 480px;"
          type="date"
          placeholder="选择营业执照成立日期"
        />
      </el-form-item>
      <el-form-item label="营业执照到期时间" prop="businessLicenseEndDate">
        <el-date-picker
          v-model="draft.businessLicenseEndDate"
          :format="businessLicenseEndDateFormat"
          style="width: 480px;"
          type="date"
          placeholder="请填写营业执照到期时间"
        />
      </el-form-item>
      <el-form-item label="公司照片" prop="companyImages" style="width: 100%;">
        <el-upload
          v-if="!(isLoading || isUpdating || !isEdit)"
          action="/api/v1/upload/file"
          list-type="picture-card"
          :on-success="uploadCompanyPhotoSuccess"
          :limit="3"
          accept=".jpg,.jpeg,.png"
          :file-list="fileList"
          :on-exceed="uploadCompanyPhotoExceed"
          :before-remove="onBeforeRemoveCompanyPhoto"
          :on-remove="onCompanyPhotoRemove"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <template v-else>
          <div v-if="draft?.companyImages?.length > 0">
            <el-image
              v-for="(item, index) in draft?.companyImages"
              :key="index"
              style="width: 150px; height: 100px; margin: 0 10px;"
              :src="item"
              fit="cover"
              :preview-src-list="draft?.companyImages"
            />
          </div>

          <div v-else>请上传公司照片</div>

        </template>

      </el-form-item>
    </el-form>
    <div class="actions">
      <template v-if="!isEdit">
        <el-button
          icon="el-icon-refresh-right"
          :disabled="isLoading"
          @click="initData"
        >
          刷新
        </el-button>

        <el-button
          icon="el-icon-edit"
          type="primary"
          :disabled="isLoading"
          @click="handleEdit"
        >
          编辑
        </el-button>
      </template>
      <template v-else>
        <el-button :disabled="isUpdating" @click="handleCancelEditing">
          取消
        </el-button>

        <el-button
          icon="el-icon-upload2"
          type="primary"
          :disabled="isUpdating"
          :loading="isUpdating"
          @click="saveDraft"
        >
          提交
        </el-button>
      </template>
    </div>
  </div>
</template>

<style lang="scss">
.companyinfo-update-register-container {
  background-color: #fff;
  .app-container-item {
    display: flex;
    align-items: center;
  }
  .app-container-enterpriseupdate-form {
    //margin-left: 120px;
    .el-form-item {
      //width: 480px;
    }
    .el-input__inner:focus {
      border-color: #8e8e8e;
      color: #8e8e8e;
    }

    .el-input__inner:focus::placeholder {
      color: #8e8e8e;
    }

    .el-input__inner:not(:focus)::placeholder {
      color: #333333;
    }

    .el-form-item__label {
      padding-right: 30px;
    }

    .el-image {
      &:first-child {
        margin: 0 10px 0 0 !important;
      }
    }
  }
  .actions {
    margin-left: 400px;
  }
}

.introduction {
  width: 800px;
  height: 300px;
  overflow: auto;
  border: 1px solid #f5f5f5;
  padding: 20px;
}
</style>
